package com.wee.aircoach_user;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.util.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.entity.MD5Util;
import com.wee.entity.User_detail;
import com.wee.entity.Version_Update;
import com.wee.fragment.MyFragment;
import com.wee.fragment.TrainingFragment;
import com.wee.fragment.find.FindFragment;


/**
 * USER MAIN PAGE, WHEN USER HAVE PLANNED
 */
public class MainActivity extends FragmentActivity implements View.OnClickListener {
/**传递参数**/
    /**
     * 保存用于3个fragment之间的传递参数
     */
    private FragmentArguments arguments = new FragmentArguments();

    /**
     * 用于在3个fragment之间传递参数
     * @author simonzhang
     *
     */
    public class FragmentArguments {
        public Integer	num;
    }

    public void setFragment(Bundle args) {

        if (args.getInt("num") != 0) {
            arguments.num = args.getInt("sex");
        }
    }
    private static final String TAG = "MainActivity";
    public FragmentArguments getFragment() {
        return arguments;
    }

    private RelativeLayout mHome;
    private ImageView mplay;
    private RelativeLayout mTabCircle;
    private ImageView mcircle;
    private RelativeLayout mTabMy;
    private  ImageView mmy;
    private RelativeLayout mfirst;
    private ImageView btn;
    private TrainingFragment mTab01;
    private FindFragment mTab02;
    private MyFragment mTab03;
    private TextView m1,m2,m3;
    private int versionCode;   //最新版的版本号
    private  String versionName;
    int verCode;
    private ProgressDialog pBar;
    private String versionUrl;
    private String versionTime;
    private Boolean versionSF;
    private String versionDiscrip;
    String  num;
    Version_Update list1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.style_mainactivity);
        isis();
        new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();
                try {
                    version();
                } catch (Exception e) {
                    e.printStackTrace();
                    Looper.loop();
                }
            }
        }).start();
      initView();
      initEvent();
      setSelect(0);
    }
     /**版本判断是否更新*/
    private void  version(){
        String url_down=Constant.Updateversion;
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url_down, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    String str = responseInfo.result;
                    Gson gs = new Gson();
                    JsonObject jo = gs.fromJson(str, JsonObject.class);
                    JsonElement je = jo.get("status");
                    String status = je.getAsString();
                    if ("ok".equals(status)) {
                        JsonObject object = jo.getAsJsonObject("data");
                        list1 = gs.fromJson(object, Version_Update.class);
                        //用于比较版本大小
                        versionCode = list1.getId();
                        //用于判断是否强制更新
                        versionSF = list1.getForce();
                        //版本升级地址
                        versionUrl = list1.getUrl();
                        //用与版本描述
                        versionDiscrip = list1.getRemark();
                        //版本升级时间
                        versionTime = list1.getUpdated_at();
                        //版本的名称
                        versionName=list1.getVer();

                        handler1.sendEmptyMessage(versionCode);
                    }

                } catch (Exception r) {
                }
            }
            @Override
            public void onFailure(HttpException e, String s) {
                System.out.println(e.getMessage());
            }
        });

    }

    /**是否第一次进入**/
    private void isis() {
       try{
           /**蒙版*/
           mfirst=(RelativeLayout)findViewById(R.id.first_model);
            findViewById(R.id.finish).setOnClickListener(this);
              num= getIntent().getStringExtra("first");
            if(num.equals("first")){
                mfirst.setVisibility(View.VISIBLE);
                Gethttp();
                mplay.setBackgroundResource(R.drawable.myplan_on);
           }
         }catch (Exception r) {

       }
     //   mplay.setBackgroundResource(R.drawable.myplan_on);
    }
    private void Gethttp() {
        int  exact=  SharedPreferencesUtil.getInt(this, com.wee.aircoach_user.Constant.USERTIME);
        String  user_main=Constant.USER_DETAIL+ MD5Util.md5(exact)+"&id="+ SharedPreferencesUtil.getInt(MainActivity.this, Constant.USERID)+"";
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {

                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            try {
                                User_detail data1 = gs.fromJson(object, User_detail.class);
                                TextView bmi = (TextView) findViewById(R.id.bmi);
                                bmi.setText(SharedPreferencesUtil.get(MainActivity.this, Constant.BMI));
                                TextView name = (TextView) findViewById(R.id.techer);
                                name.setText(data1.getCoach().getName());
                                TextView dongzuo = (TextView) findViewById(R.id.dongzuo);
                                dongzuo.setText(data1.getPlan().getName());
                            } catch (Exception r) {
                            }

                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });
    }

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            verCode= Common.getVerCode(getApplicationContext());
            if (msg.what>verCode) {
                showUpdateDialog();  //下面的代码段
            }else {
               // Toast.makeText(MainActivity.this, "当前已是最新版本..", Toast.LENGTH_SHORT).show();
            }
        }

    };
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle("请升级APP至版本" + versionName);
        builder.setMessage(""+versionDiscrip);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    demo
                            (versionUrl);     //在下面的代码段
                } else {
                    Toast.makeText(MainActivity.this, "SD卡不可用，请插入SD卡",
                            Toast.LENGTH_SHORT).show();
                }
            }

            private void demo(String url) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);

            }
        });
        //强制升级可操作
        if(!versionSF){
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
        }
        builder.create().show();
    }

    private void initEvent() {
        mHome.setOnClickListener(this);
        mTabCircle.setOnClickListener(this);
        mTabMy.setOnClickListener(this);
    }

    private void initView() {
         m1= (TextView) findViewById(R.id.mainben);
        m2= (TextView) findViewById(R.id.mainfa);
        m3= (TextView) findViewById(R.id.mainwo);

        mplay= (ImageView) findViewById(R.id.play);
        mcircle= (ImageView) findViewById(R.id.cirlce);
        mmy= (ImageView) findViewById(R.id.my);

        mHome = (RelativeLayout) findViewById(R.id.id_training);
        mTabCircle = (RelativeLayout) findViewById(R.id.id_circle);
        mTabMy = (RelativeLayout) findViewById(R.id.id_my);


    }

    private void setSelect(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);


        switch (i) {
            case 0:
                if (mTab01 == null) {
                    mTab01 = new TrainingFragment();
                    transaction.add(R.id.id_content, mTab01);
                } else {
                    transaction.show(mTab01);
                }
                mplay.setBackgroundResource(R.drawable.myplan_on);
                m1.setTextColor(Color.rgb(255, 82, 0));
                mTab01.setSkipCall(new TrainingFragment.SkipCall() {

                    @Override
                    public void skipTo(boolean isTrue) {
                        if (isTrue) {
                            setSelect(1);
                            mplay.setBackgroundResource(R.drawable.myplan_no);
                            m1.setTextColor(Color.rgb(118, 118, 118));
                        }
                }
                });
                break;
            case 1:
                if (mTab02 == null) {
                    mTab02 = new FindFragment();
                    transaction.add(R.id.id_content, mTab02);
                } else {
                    transaction.show(mTab02);

                }
                mcircle.setBackgroundResource(R.drawable.faxian_on);
                m2.setTextColor(Color.rgb(255, 82, 0));
                break;
            case 2:
                if (mTab03 == null) {
                    mTab03 = new MyFragment();
                    transaction.add(R.id.id_content, mTab03);
                } else {
                    transaction.show(mTab03);
                }
                mmy.setBackgroundResource(R.drawable.me_on);
                m3.setTextColor(Color.rgb(255, 82, 0));
                break;


            default:
                break;
        }

        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mTab01 != null) {
            transaction.hide(mTab01);
        }
        if (mTab02 != null) {
            transaction.hide(mTab02);
        }
        if (mTab03 != null) {
            transaction.hide(mTab03);
        }

    }

    @Override
    public void onClick(View v) {
        resetImgs();
        switch (v.getId()) {
            case R.id.id_training:
                setSelect(0);
                break;
            case R.id.id_circle:
                setSelect(1);
                break;
            case R.id.id_my:
                setSelect(2);
                break;
            case R.id.finish:
                mfirst.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }



    /**
     * �л�ͼƬ����ɫ
     */
    private void resetImgs() {
        mplay.setBackgroundResource(R.drawable.myplan_no);
        m1.setTextColor(Color.rgb(118, 118, 118));
        mcircle.setBackgroundResource(R.drawable.faxian_no);
        m2.setTextColor(Color.rgb(118, 118, 118));
        mmy.setBackgroundResource(R.drawable.me_no);
        m3.setTextColor(Color.rgb(118, 118, 118));
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
             Log.d(TAG, "onAttachFragment");

             if (mTab01 == null && fragment instanceof TrainingFragment) {
                      mTab01 = (TrainingFragment)fragment;
                    }else if (mTab02 == null && fragment instanceof FindFragment) {
                       mTab02 = (FindFragment)fragment;
                   }else if (mTab03 == null && fragment instanceof MyFragment) {
                       mTab03 = (MyFragment)fragment;
                   }

    }
}

